package com.service.impl;

import com.entity.ProductEs;
import com.service.ProductEsService;
import config.MqConfig;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProductEsServiceImpl implements ProductEsService {
    @Override
    public void insertDoc(ProductEs productEs) {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("name", productEs.getName());
        jsonMap.put("productDesc", productEs.getProductDesc());
        jsonMap.put("id", productEs.getId());

        try (RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http")))) {
            IndexRequest request = new IndexRequest(MqConfig.ES_MQ_DEMO)
                    .id(productEs.getId().toString()).source(jsonMap);
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            //System.out.println(response .getId());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
